function resize_login_form(staticHeight) {
    if (staticHeight != undefined) {
            $('#login-content').height(staticHeight);
    } else {
        if ($('#login-content').height() > $(window).height()) {
            $('#login-content').height($(window).height() - 100);
        }
    }
}

function login_form() {
    $(document).ready(function() {
        $('#create-ajax-user-submit').live('click', function() {
            create_ajax_user($('#create-ajax-user'));
        });

        $('#edit-ajax-user-submit').live('click', function() {
            edit_ajax_user($('#edit-ajax-user'));
        });

        $('#try-login').live('click', function() {
            login_user($('#login-part'));
        });

        $('#send-password').live('click', function() {
            send_password($('#password-reminder-part'));
        });


        $('.disconnect').live('click', function() {
            ajax('disconnect.php', {
                'query': 'disconnect'
            }, function(data) {
                erraAlert(getRest(data)['message']);
                window.location.reload();
            });
        });

        $('#login-display').live('click', function() {
            if (!$('#login-part').is(':visible')) {
                $('#register-part').hide();
                $('#password-reminder-part').hide();
                $('#login-part').fadeIn();
                $('#login-display').css('border', '1px solid grey');
                $('#register-display').css('border', 'none');
                resize_login_form(230); 
            }
        });

        $('#register-display').live('click', function() {
            if (!$('#register-part').is(':visible')) {
                $('#login-part').hide();
                $('#password-reminder-part').hide();
                $('#register-part').fadeIn();
                $('#register-display').css('border', '1px solid grey');
                $('#login-display').css('border', 'none');
                resize_login_form();
            }
        });

        $('#retour-mot-de-passe').live('click', function() {
            $('#login-part').hide();
            $('#register-part').hide();
            $('#password-reminder-part').fadeIn();
        });

        $('#retour-connexion').live('click', function() {
            $('#register-part').hide();
            $('#password-reminder-part').hide();
            $('#login-part').fadeIn();
        });
    });
    $(window).resize(function() {
        resize_login_form();
    });
}

function send_password($form) {
    $mail_address = $form.find('#mail_address');
    if (!validateEmail($mail_address.val())) {
        setError($mail_address, 'Veuillez entrer une adresse mail valide');
    } else {
        removeError($mail_address);
        ajax(GATEWAY_URL, {
            'query': 'send_password',
            'mail_address': $mail_address.val()
        }, function(data) {
            if (getRest(data)['code'] == 200) { // OK
                $mail_address.val('');
                erraAlert(getRest(data)['message']);
            } else {
                erraAlert(getRest(data)['message']);
            }
        });
    }

}

function login_user($form) {
    $login = $form.find('#login');
    $password = $form.find('#password');


    if (!validateEmail($login.val())) {
        setError($login, 'Veuillez entrer une adresse mail valide');
    } else {
        removeError($login);
    }
    if (!$password.val().length) {
        setError($password, 'Veuillez entrer un mot de passe');
    } else {
        removeError($password);
    }

    if (!bErrors([$login, $password])) {
        ajax(GATEWAY_URL, {
            'query': 'login_user',
            'login': $login.val(),
            'password': $password.val()
        }, function(data) {
            if (getRest(data)['code'] == 200) { // OK
                response = getResponse(data);
                $('#profil').html(response);
                ajax_form_reset($form);
                ajax('login.php', {
                    'content': response
                }, function(result) {
                    ajaxForce(GATEWAY_URL, {
                        'query': 'get_user_header',
                        'object_id': result
                    }, function(data) {
                        $('.header .espace-client').html(data);
                        $('#user_session').html(result);
                    });
                    // Check login content to see if next step exists
                    if ($('#login-content').length && $('#login-content').attr('data-resa-timestamp') != undefined) {
                        confirm_rdv_dialog();
                    }
                    $('#login-dialog').dialog('close');

                });
            } else {
                erraAlert(getRest(data)['message']);
            }
        });
    }
}


function edit_ajax_user($form) {
    post_array = $form.find('select, input, textarea').serializeArray();

    $nom = $form.find('#nom');
    $prenom = $form.find('#prenom');
    $telephone = $form.find('#telephone_portable');
    $telephone_fixe = $form.find('#telephone_fixe');
    
    if (!$nom.val().length) {
        setError($nom, 'Veuillez entrer votre nom');
    } else {
        removeError($nom);
    }
        if ($telephone.val().length && !is_french_phone($telephone.val())) {
        setError($telephone, 'Veuillez entre un numéro de portable valide');
    } else {
        removeError($telephone);
    }
    
    if ($telephone_fixe.val().length && !is_french_phone($telephone_fixe.val())) {
        setError($telephone_fixe, 'Veuillez entre un numéro de téléphone valide');
    } else {
        removeError($telephone_fixe);
    }
    if (!$prenom.val().length) {
        setError($prenom, 'Veuillez entrer votre prénom');
    } else {
        removeError($prenom);
    }
    if (!bErrors([$prenom, $nom, $telephone, $telephone_fixe])) {
        ajax(GATEWAY_URL, {
            query: 'edit_ajax_user',
            data: post_array
        }, function(data) {
            ajax_edit_user_end($form, data);
        });
    }
}

function create_ajax_user($form) {
    post_array = $form.find('select, input, textarea').serializeArray();

    $nom = $form.find('#nom');
    $prenom = $form.find('#prenom');
    $email = $form.find('#email');
    $mot_de_passe = $form.find('#mot_de_passe');
    $mot_de_passe_confirm = $form.find('#mot_de_passe_confirm');
    $telephone = $form.find('#telephone_portable');
    $telephone_fixe = $form.find('#telephone_fixe');

    if (!$nom.val().length) {
        setError($nom, 'Veuillez entrer un nom pour ce client');
    } else {
        removeError($nom);
    }
    if (!$prenom.val().length) {
        setError($prenom, 'Veuillez entrer un prénom pour ce client');
    } else {
        removeError($prenom);
    }

    if ($telephone.val().length && !is_french_phone($telephone.val())) {
        setError($telephone, 'Veuillez entre un numéro de portable valide');
    } else {
        removeError($telephone);
    }
    
    if ($telephone_fixe.val().length && !is_french_phone($telephone_fixe.val())) {
        setError($telephone_fixe, 'Veuillez entre un numéro de téléphone valide');
    } else {
        removeError($telephone_fixe);
    }
    if ($mot_de_passe.val().length < 4) {
        setError($mot_de_passe, 'Le mot de passe doit faire au moins 4 caractères');
    } else {
        removeError($mot_de_passe);
        if (!ctype_alnum($mot_de_passe.val())) {
            setError($mot_de_passe, 'Le mot de passe ne comprendre que des chiffres et des lettres');
        } else {
            removeError($mot_de_passe);
            if ($mot_de_passe.val() != $mot_de_passe_confirm.val()) {
                setError($mot_de_passe, 'Les mots de passe ne correspondent pas');
            } else {
                removeError($mot_de_passe);
            }
        }

    }
    var emailChecked = false;
    var disabledEmail = ($email.attr('readonly') == 'readonly') ? true : false;

    if ($email.val().length && !disabledEmail) {
        if (!validateEmail($email.val())) {
            setError($email, 'Veuillez entrer une adresse mail valide');
        } else {
            removeError($email);
            emailChecked = true;
            ajax(GATEWAY_URL, {
                query: 'check_ajax_user',
                email: $email.val()
            }, function(data) {
                if (getRest(data)['code'] == 306) { // Reserved
                    setError($email, "L'adresse e-mail existe déja");
                }
            }, function() {
                if (!bErrors([$prenom, $email, $nom, $mot_de_passe, $telephone, $telephone_fixe])) {
                    post_array['query'] = 'create_ajax_user';
                    ajax(GATEWAY_URL, {
                        query: 'create_ajax_user',
                        data: post_array
                    }, function(data) {
                        ajax_user_end_process($form, data);
                    });
                }
            });
        }
    } else {
        setError($email, "Veuillez entrer une adresse e-mail");
    }
}

function ajax_user_end_process($form, data) {
    if (getRest(data)['code'] == 200) {
        // Feed session data
        data = getResponse(data);
        $('#profil').html(data);
        // Put header
        var userObjectId = $(data).find('input[name="object_id"]').val();
        ajaxForce(GATEWAY_URL, {
            'query': 'get_user_header',
            'object_id': userObjectId
        }, function(data) {
            $('.header .espace-client').html(data);
        });

        ajax_form_reset($form);
        // SET SESSION INFOS
        ajax('login.php', {
            'content': data
        }, function(result) {
            // Check login content to see if next step exists
            if ($('#login-content').length && $('#login-content').attr('data-resa-timestamp') != undefined) {
                confirm_rdv_dialog();
            }
            $('#login-dialog').dialog('close');
        });
    }
}

function ajax_edit_user_end($form, data) {
    if (getRest(data)['code'] == 200) {
        erraAlert(getRest(data)['message']);
    }
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}




function getSessionData(new_location) {
    currentData = new Array();
    $('#shop_session input').each(function() {
        if (new_location != undefined && !isNaN(new_location)) {
            // Update shop ID
            $(this).attr('data-shop_id', new_location);
            currentData.push({
                'shop_id': $(this).attr('data-shop_id'),
                'prestation_id': $(this).attr('data-presta-id'),
                'uniqid': $(this).attr('data-uniqid')
            });
        } else {
            currentData.push({
                'shop_id': $(this).attr('data-shop_id'),
                'prestation_id': $(this).attr('data-presta-id'),
                'uniqid': $(this).attr('data-uniqid')
            });
        }
    });
    return currentData;
}
function getExtraFields(fn) {
    extraFields = {};
    var jqXHRs = $('#confirm-dialog-content').find('[name^="extra_field_"]').each(function() {
        var name = $(this).attr('name');
        var val = $(this).val();
        if ($(this).attr('type') != undefined && ($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox')) {
            if ($(this).attr('checked')) {
                extraFields[name] = val;
            }
        } else {
            extraFields[name] = val;
        }
    });
    $.when.apply(null, jqXHRs.get()).done(fn(extraFields));
}

function stdBookRdv(bPaypalIsActive) {
    getExtraFields(function(extraFields) {
        var userId = $('#edit-ajax-user').find('input[name="object_id"]').val();
        ajax(GATEWAY_URL, {
            'query': 'book_rdv',
            'agenda_id': $('#selected_agenda').val(),
            'rdv_data': currentData,
            'realStart': selectedDate,
            'client_id': userId,
            'extra_fields': extraFields
        }, function(data) {
            if (getRest(data)['code'] == 200) {
                if (bPaypalIsActive === 1) {
                    gotoPaypal();
                } else {
                    var message = getRest(data)['message'];
                    redirection_url = '';
                    if (message.indexOf('htt') > 0) {
                        redirection_url = message.substring(message.indexOf('htt'), message.length);
                        message = message.replace(redirection_url, '');
                    }
                    erraAlertModal(message, function() {
                        $("#message").dialog("close");
                        $("#confirm-dialog").dialog("close");
                        if (redirection_url != undefined && redirection_url.length) {
                            location.href = redirection_url;
                        } else {
                            location.reload();
                        }
                    });
                }
            } else {
                erraAlert(getRest(data)['message']);
                post_init();
            }
        });
    });
}

function gotoPaypal() {
    if ($('#pay_paypal_container').find('form').length) {
        $('#pay_paypal_container').find('form').submit();
    }
}

function createPaypalForm() {
    var paypalData = $('#paypal_session').html();
    var userSession = $('#user_session').html();
    paypalForm = '';
    if (paypalData.length && userSession.length) {
        paypalData = json_decode(paypalData);
        paypalVendor = paypalData.paypal_vendor_id;
        currentData = getSessionData();
        created_prestas = userSession + ';';
        if (currentData.length) {
            for (i = 0; i < currentData.length; i++) {
                created_prestas += currentData[i]['uniqid'] + ';';
            }
            var prestaStr = $('.shop_name').html() + ' | ';
            var prestaArray = new Array();
            var price = 0;
            each($('#cart-infos .prestation-small .title'), function($this) {
                prestaArray.push($this.html());
            });
            each($('#cart-infos .prestation-small .prix'), function($this) {
                presta_price = extractNumbers($this.html());
                if (!isNaN(parseFloat(presta_price))) {
                    price += parseFloat(presta_price);
                }
            });
            prestaStr += implode(',', prestaArray);
            // Form
            //' + paypalVendor + '">';
            paypalForm += '<input type="hidden" name="currency_code" value="EUR">';
            paypalForm = '<form id="pay_paypal" name="_xclick" action="https://www.paypal.com/cgi-bin/webscr" method="post">';

            paypalForm += '<input type="hidden" name="cmd" value="_xclick">';
            paypalForm += '<input type="hidden" name="business" value="' + paypalVendor + '">';
            paypalForm += '<input type="hidden" name="currency_code" value="EUR">';
            paypalForm += '<input type="hidden" name="item_name" value="' + prestaStr + '">';
            paypalForm += '<input type="hidden" name="amount" value="' + price + '">';
            paypalForm += '<input type="hidden" name="custom" value="' + created_prestas + '">';
            paypalForm += '<input type="hidden" name="return" value="' + FRONT_URL + '">';
            paypalForm += '<input type="hidden" name="notify_url" value="' + IPN_URL + '">';
            paypalForm += '</form>';
        }
    }
    return paypalForm;
}

function confirm_rdv_dialog() {
    selectedDate = $('#login-content').attr('data-resa-timestamp');
    matchAgendas = $('#login-content').attr('data-agenda-match');
    currentData = getSessionData();
    // TODO : DO WHATS NECESSARY HERE alert(matchAgendas);
    extraFields = new Array();
    post_array = {
        'query': 'final_rdv_dialog',
        'client_id': $('#user_session').html(),
        'date_selected': selectedDate,
        'match_agendas': matchAgendas,
        'rdv_data': currentData
    };
    if ($('#paypal_session').html().length) {
        var paypalData = $('#paypal_session').html();
        paypalData = json_decode(paypalData);
        paypalMode = paypalData.paypal_mode;
    }
    ajax(GATEWAY_URL, post_array,
            function(data) {
                if (getRest(data)['code'] == 200) {
                    response = getResponse(data);
                    $('#confirm-dialog-content').html(response);
                    if (!$('#user_session').html().length) {
                        $('#confirm-dialog-content').prepend('<font color="green"><strong>Le compte utilisateur a correctement été créé</strong></font><br/><br/>');
                    }
                    var paypalForm = '';
                    if (paypalMode == 0) {
                        bookButtons = {
                            "Confirmer": function() {
                                stdBookRdv(0)
                            },
                            "Annuler": function() {
                                $(this).dialog("close");
                            }
                        };
                    } else if (paypalMode == 1) {
                        $('#confirm-dialog-content').append('<br/><strong>Vous devez payer en ligne via PayPal pour que votre reservation soit validée</strong>');
                        $('#pay_paypal_container').append(createPaypalForm());
                        bookButtons = {
                            "Confirmer et payer en ligne": function() {
                                stdBookRdv(1);
                            },
                            "Annuler": function() {
                                $(this).dialog("close");
                            }
                        };
                    } else {
                        $('#confirm-dialog-content').append('<br/><strong>Vous pouvez si vous le souhaitez payer vos prestations dès maintenant via PayPal</strong>');
                        $('#pay_paypal_container').append(createPaypalForm());
                        bookButtons = {
                            "Confirmer et payer en ligne": function() {
                                stdBookRdv(1);
                            },
                            "Confirmer et payer surplace": function() {
                                stdBookRdv(0);
                            },
                            "Annuler": function() {
                                $(this).dialog("close");
                            }
                        };
                    }
                    $('#confirm-dialog').dialog({
                        width: 500,
                        modal: true,
                        position: 'top',
                        buttons: bookButtons
                    });
                } else {
                    erraAlert('Impossible de finaliser la réservation en ligne, veuilez rééssayer plus tard');
                }
            });
}
